<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>期末周 - 网页版</title>
    <!-- 添加音频文件 -->
    <audio id="bgm" loop>
        <source src="{{ url_for('static', filename='audio/bgm.mp3') }}" type="audio/mpeg">
        您的浏览器不支持音频元素。
    </audio>
    <style>
        :root {
            --primary-color: #4a90e2;
            --secondary-color: #6c757d;
            --success-color: #28a745;
            --danger-color: #dc3545;
            --warning-color: #ffc107;
            --info-color: #17a2b8;
            --light-color: #f8f9fa;
            --dark-color: #343a40;
            --health-color: #e74c3c;
            --energy-color: #f39c12;
            --knowledge-color: #3498db;
        }
        
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        body {
            font-family: "Microsoft YaHei", Arial, sans-serif;
            background: linear-gradient(135deg, #74b9ff, #0984e3);
            color: #333;
            line-height: 1.6;
            padding: 20px;
            min-height: 100vh;
        }
        
        .container {
            max-width: 900px;
            margin: 0 auto;
            background-color: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            overflow: hidden;
        }
        
        .header {
            background: linear-gradient(to right, #4a90e2, #6a5acd);
            color: white;
            text-align: center;
            padding: 20px;
            position: relative;
        }
        
        /* 添加BGM控制按钮样式 */
        .bgm-control {
            position: absolute;
            top: 10px;
            right: 10px;
            background: rgba(255, 255, 255, 0.2);
            border: none;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            font-size: 20px;
            cursor: pointer;
            color: white;
            transition: all 0.3s ease;
        }
        
        .bgm-control:hover {
            background: rgba(255, 255, 255, 0.3);
            transform: scale(1.1);
        }
        
        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
        }
        
        .status-bar {
            display: flex;
            justify-content: space-between;
            background-color: #e3f2fd;
            padding: 15px;
            border-bottom: 2px solid #dee2e6;
        }
        
        .status-item {
            text-align: center;
            flex: 1;
        }
        
        .status-label {
            font-weight: bold;
            margin-bottom: 5px;
            color: #495057;
        }
        
        .progress-container {
            height: 20px;
            background-color: #ddd;
            border-radius: 10px;
            overflow: hidden;
            margin-top: 5px;
        }
        
        .progress-bar {
            height: 100%;
            border-radius: 10px;
            transition: width 0.5s ease;
        }
        
        .health-bar { 
            background-color: var(--health-color); 
        }
        
        .energy-bar { 
            background-color: var(--energy-color); 
        }
        
        .knowledge-bar { 
            background-color: var(--knowledge-color); 
        }
        
        .screen {
            display: none;
            padding: 20px;
        }
        
        .active {
            display: block;
        }
        
        .menu {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        
        .menu-title {
            text-align: center;
            margin-bottom: 20px;
            color: #495057;
            font-size: 1.5rem;
        }
        
        .menu-buttons {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
        }
        
        .btn {
            padding: 12px 20px;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            cursor: pointer;
            transition: all 0.3s ease;
            text-align: center;
            font-weight: bold;
        }
        
        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
        }
        
        .btn:active {
            transform: translateY(0);
        }
        
        .btn-primary {
            background-color: var(--primary-color);
            color: white;
        }
        
        .btn-secondary {
            background-color: var(--secondary-color);
            color: white;
        }
        
        .btn-success {
            background-color: var(--success-color);
            color: white;
        }
        
        .btn-danger {
            background-color: var(--danger-color);
            color: white;
        }
        
        .btn-warning {
            background-color: var(--warning-color);
            color: #212529;
        }
        
        .inventory {
            background-color: #fff3cd;
            border: 1px solid #ffeaa7;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        
        .inventory h3 {
            margin-bottom: 10px;
            color: #856404;
        }
        
        .inventory-items {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
            gap: 10px;
        }
        
        .inventory-item {
            background-color: #fff;
            padding: 10px;
            border-radius: 5px;
            border: 1px solid #dee2e6;
        }
        
        .message-box {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        
        .exam-info {
            background-color: #cce5ff;
            border: 1px solid #99ccff;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        
        .day-info {
            background-color: #e2e3e5;
            border: 1px solid #d6d8db;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
            text-align: center;
        }
        
        .event-box {
            background-color: #d1ecf1;
            border: 1px solid #bee5eb;
            padding: 15px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        
        .actions {
            display: flex;
            justify-content: center;
            gap: 10px;
            flex-wrap: wrap;
            margin-top: 20px;
        }
        
        h1, h2, h3 {
            color: #2c3e50;
            margin-bottom: 15px;
        }
        
        .center {
            text-align: center;
        }
        
        .score-display {
            font-size: 1.2rem;
            font-weight: bold;
            text-align: center;
            padding: 10px;
            background-color: #e9ecef;
            border-radius: 5px;
            margin-bottom: 20px;
        }
        
        .item-list {
            list-style: none;
        }
        
        .item-list li {
            padding: 8px;
            margin: 5px 0;
            background-color: #f8f9fa;
            border-radius: 5px;
            border: 1px solid #dee2e6;
        }
        
        .hidden {
            display: none;
        }
        
        .ending-cg {
            max-width: 100%;
            height: auto;
            margin-top: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
            display: none;
        }
        
        .game-over {
            text-align: center;
            padding: 20px;
        }
        
        .game-over h2 {
            color: var(--danger-color);
            font-size: 2rem;
            margin-bottom: 20px;
        }
        
        .final-score {
            font-size: 1.5rem;
            font-weight: bold;
            margin: 20px 0;
        }
        
        /* 天数节点UI样式 */
        .days-progress {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin: 20px 0;
            position: relative;
        }
        
        .days-progress::before {
            content: "";
            position: absolute;
            top: 50%;
            left: 0;
            right: 0;
            height: 4px;
            background-color: #ddd;
            transform: translateY(-50%);
            z-index: 1;
        }
        
        .day-node {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background-color: #ccc;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            color: white;
            z-index: 2;
            border: 2px solid #fff;
        }
        
        .day-node.current {
            background-color: var(--primary-color);
            transform: scale(1.2);
        }
        
        .day-node.completed {
            background-color: var(--success-color);
        }
        
        /* 老师选择界面样式 */
        .teacher-selection {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            margin: 20px 0;
            text-align: center;
        }
        
        .teacher-options {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-top: 20px;
            flex-wrap: wrap;
        }
        
        .teacher-card {
            background: white;
            border-radius: 15px;
            padding: 25px;
            width: 280px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            cursor: pointer;
            transition: all 0.3s ease;
            border: 3px solid transparent;
            position: relative;
            overflow: hidden;
        }
        
        .teacher-card:hover {
            transform: translateY(-10px);
            box-shadow: 0 10px 25px rgba(0,0,0,0.2);
        }
        
        .teacher-card.selected {
            border-color: var(--primary-color);
            background-color: #e3f2fd;
        }
        
        .teacher-card.strict {
            border-top: 5px solid var(--danger-color);
        }
        
        .teacher-card.kind {
            border-top: 5px solid var(--success-color);
        }
        
        .teacher-icon {
            font-size: 3rem;
            margin-bottom: 15px;
        }
        
        .teacher-card.strict .teacher-icon {
            color: var(--danger-color);
        }
        
        .teacher-card.kind .teacher-icon {
            color: var(--success-color);
        }
        
        .teacher-card h3 {
            margin-top: 0;
            color: #495057;
            font-size: 1.4rem;
        }
        
        .teacher-card.strict h3 {
            color: #c00;
        }
        
        .teacher-card.kind h3 {
            color: #28a745;
        }
        
        .teacher-description {
            font-size: 1rem;
            margin: 15px 0;
            min-height: 60px;
            color: #6c757d;
        }
        
        .teacher-effect {
            font-size: 0.95rem;
            margin-top: 15px;
            padding: 12px;
            background-color: #e9ecef;
            border-radius: 8px;
            border-left: 4px solid #6c757d;
        }
        
        .teacher-card.strict .teacher-effect {
            background-color: #f8d7da;
            border-left-color: var(--danger-color);
        }
        
        .teacher-card.kind .teacher-effect {
            background-color: #d4edda;
            border-left-color: var(--success-color);
        }
        
        .effect-value {
            display: inline-block;
            font-weight: bold;
            margin: 0 3px;
        }
        
        .effect-positive {
            color: var(--success-color);
        }
        
        .effect-negative {
            color: var(--danger-color);
        }
        
        .actions-counter {
            background-color: #ff6b6b;
            color: white;
            padding: 5px 15px;
            border-radius: 20px;
            font-weight: bold;
            font-size: 1.1rem;
            box-shadow: 0 3px 6px rgba(0,0,0,0.2);
            border: 2px solid #fff;
            display: inline-block;
            min-width: 40px;
            text-align: center;
        }
        
        .actions-counter-container {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            padding: 10px 20px;
            border-radius: 30px;
            display: inline-block;
            box-shadow: 0 4px 12px rgba(0,0,0,0.3);
            margin-bottom: 15px;
        }
        
        .actions-counter-label {
            color: white;
            font-weight: bold;
            margin-right: 10px;
            text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
        }
        
        /* 考试提醒动画样式 */
        .exam-alert {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: #fff3cd;
            border: 2px solid #ffc107;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            z-index: 1000;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            animation: examAlert 0.5s ease-in-out;
            display: none;
        }
        
        .exam-alert.show {
            display: block;
        }
        
        @keyframes examAlert {
            0% { transform: translate(-50%, -50%) scale(0.5); opacity: 0; }
            50% { transform: translate(-50%, -50%) scale(1.1); }
            100% { transform: translate(-50%, -50%) scale(1); opacity: 1; }
        }
        
        .exam-alert h3 {
            color: #856404;
            margin-bottom: 10px;
        }
        
        .exam-alert p {
            margin-bottom: 15px;
        }
        
        @media (max-width: 768px) {
            .status-bar {
                flex-direction: column;
                gap: 10px;
            }
            
            .menu-buttons {
                grid-template-columns: 1fr;
            }
        }
        
        /* 随堂测试模态框样式 */
        .modal {
            display: block;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }
        
        .modal-content {
            background-color: #fff;
            margin: 15% auto;
            padding: 20px;
            border-radius: 10px;
            width: 80%;
            max-width: 500px;
            text-align: center;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }
        
        .quiz-options {
            display: flex;
            flex-direction: column;
            gap: 10px;
            margin-top: 20px;
        }
        
        .quiz-option {
            background-color: var(--primary-color);
            color: white;
            border: none;
            padding: 12px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 1rem;
            transition: background-color 0.3s;
        }
        
        .quiz-option:hover {
            background-color: #3a7bc8;
        }
        
        .ending-content {
            text-align: center;
            padding: 20px;
        }
        
        .ending-cg {
            max-width: 100%;
            height: auto;
            margin-top: 20px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }
        
        .final-stats {
            background-color: #e9ecef;
            padding: 15px;
            border-radius: 10px;
            margin: 20px 0;
        }
        
        .action-buttons {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
            gap: 15px;
            padding: 20px;
        }
        
        .action-btn {
            background-color: var(--primary-color);
            color: white;
            border: none;
            padding: 15px;
            border-radius: 10px;
            cursor: pointer;
            font-size: 1rem;
            font-weight: bold;
            transition: all 0.3s ease;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .action-btn:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 8px rgba(0, 0, 0, 0.15);
        }
        
        .action-btn:active {
            transform: translateY(1px);
        }
        
        .action-btn.study {
            background-color: #28a745;
        }
        
        .action-btn.rest {
            background-color: #ffc107;
            color: #212529;
        }
        
        .action-btn.quiz {
            background-color: #6f42c1;
        }
        
        .action-btn.save {
            background-color: #17a2b8;
        }
        
        .action-btn.load {
            background-color: #6c757d;
        }
        
        .study-btn {
            background-color: #3498db;
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            margin: 5px;
            transition: all 0.3s ease;
            width: calc(50% - 10px);
        }
        
        .study-btn:hover {
            background-color: #2980b9;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }
        
        .study-btn:active {
            transform: translateY(0);
        }
        
        .study-quiz-container {
            background-color: #e8f4fc;
            border-radius: 10px;
            padding: 20px;
            margin: 20px 0;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
            display: none;
        }
        
        .study-quiz-question {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 15px;
            color: #2c3e50;
        }
        
        .study-quiz-options {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        
        .study-quiz-option {
            background-color: white;
            border: 2px solid #3498db;
            border-radius: 8px;
            padding: 12px;
            cursor: pointer;
            transition: all 0.2s ease;
        }
        
        .study-quiz-option:hover {
            background-color: #3498db;
            color: white;
        }
        
        .study-quiz-option.selected {
            background-color: #3498db;
            color: white;
            border-color: #2980b9;
        }
        
        .submit-answer-btn {
            background-color: #27ae60;
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            margin-top: 15px;
            transition: all 0.3s ease;
            width: 100%;
        }
        
        .submit-answer-btn:hover {
            background-color: #219653;
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
        }
        
        .submit-answer-btn:disabled {
            background-color: #bdc3c7;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🎓 期末周</h1>
            <p>这是一场关于生存与学习的挑战，你需要通过7天的考验</p>
            <button class="bgm-control" onclick="toggleBGM()">🔇</button>
        </div>
        
        <!-- 考试时间提醒 -->
        <div class="exam-alert" id="exam-alert">
            <h3>⏰ 考试时间到了！</h3>
            <p>你已经用完了今天的操作次数，现在只能参加考试或使用道具了</p>
            <button class="btn btn-primary" onclick="closeExamAlert()">确定</button>
        </div>
        
        <!-- 玩家状态栏 -->
        <div class="status-bar">
            <div class="status-item">
                <div class="status-label">❤️ 生命值</div>
                <div class="progress-container">
                    <div class="progress-bar health-bar" id="health-bar" style="width: 100%;"></div>
                </div>
                <div id="health-text">100/100</div>
            </div>
            
            <div class="status-item">
                <div class="status-label">⚡ 精力值</div>
                <div class="progress-container">
                    <div class="progress-bar energy-bar" id="energy-bar" style="width: 100%;"></div>
                </div>
                <div id="energy-text">100/100</div>
            </div>
            
            <div class="status-item">
                <div class="status-label">📚 知识值</div>
                <div class="progress-container">
                    <div class="progress-bar knowledge-bar" id="knowledge-bar" style="width: 0%;"></div>
                </div>
                <div id="knowledge-text">0</div>
            </div>
            
            <div class="status-item">
                <div class="status-label">🏅 分数</div>
                <div id="score-text">0</div>
            </div>
            
            <div class="status-item">
                <div class="status-label">📅 天数</div>
                <div id="day-text">第1天</div>
            </div>
        </div>
        
        <!-- 天数节点进度条 -->
        <div class="days-progress" id="days-progress">
            <div class="day-node" id="day-node-1">1</div>
            <div class="day-node" id="day-node-2">2</div>
            <div class="day-node" id="day-node-3">3</div>
            <div class="day-node" id="day-node-4">4</div>
            <div class="day-node" id="day-node-5">5</div>
            <div class="day-node" id="day-node-6">6</div>
            <div class="day-node" id="day-node-7">7</div>
        </div>
        
        <!-- 老师选择界面 -->
        <div id="teacher-selection-screen" class="screen">
            <div class="menu">
                <h2 class="menu-title">🧙‍♂️ 选择你的老师 🧙‍♀️</h2>
                <button id="bgm-control" class="bgm-control">⏸️</button>
                <p style="text-align: center; margin-bottom: 20px; font-size: 1.1rem; color: #6c757d;">不同的老师将带来不同的学习体验，选择适合你的风格！</p>
                
                <!-- 添加游戏玩法介绍 -->
                <div style="background-color: #e3f2fd; border-radius: 10px; padding: 20px; margin-bottom: 20px; border-left: 4px solid #4a90e2;">
                    <h3 style="color: #4a90e2; margin-top: 0;">🎮 游戏玩法介绍</h3>
                    <ul style="text-align: left; padding-left: 20px;">
                        <li>你需要在7天内通过期末考试的挑战</li>
                        <li>每天可以进行最多7次操作：复习功课、休息恢复、使用道具等</li>
                        <li>通过复习可以增加知识值，但会消耗精力值</li>
                        <li>通过休息可以恢复精力值，但要注意时间管理</li>
                        <li>参加随堂测试可以获取额外奖励</li>
                        <li>合理使用道具可以帮助你更好地应对考试</li>
                        <li>保持生命值，避免因过度劳累而游戏结束</li>
                        <li>在第7天结束时，根据你的知识值和表现进行评分</li>
                    </ul>
                    <p style="font-weight: bold; color: #e74c3c;">🎯 目标：合理安排时间，平衡学习与休息，争取获得最好的成绩！</p>
                </div>
                
                <div class="teacher-options">
                    <div class="teacher-card strict" onclick="selectTeacher('strict')" id="teacher-strict">
                        <div class="teacher-icon">⚔️</div>
                        <h3>严厉但教学很好</h3>
                        <p class="teacher-description">严格要求，但能学到真本领</p>
                        <div class="teacher-effect">
                            <p><strong>学习效果：</strong></p>
                            <p>
                                <span class="effect-value effect-negative">精力 -15</span>
                                <span> ➜ </span>
                                <span class="effect-value effect-positive">知识 +20</span>
                            </p>
                            <p style="margin-top: 10px; font-size: 0.85rem; color: #6c757d;">
                                ⭐ 学习效率更高，但更累
                            </p>
                        </div>
                    </div>
                    
                    <div class="teacher-card kind" onclick="selectTeacher('kind')" id="teacher-kind">
                        <div class="teacher-icon">😊</div>
                        <h3>和蔼可亲</h3>
                        <p class="teacher-description">温和教学，循序渐进</p>
                        <div class="teacher-effect">
                            <p><strong>学习效果：</strong></p>
                            <p>
                                <span class="effect-value effect-negative">精力 -10</span>
                                <span> ➜ </span>
                                <span class="effect-value effect-positive">知识 +15</span>
                            </p>
                            <p style="margin-top: 10px; font-size: 0.85rem; color: #6c757d;">
                                ⭐ 平衡发展，轻松学习
                            </p>
                        </div>
                    </div>
                </div>
                
                <div style="text-align: center; margin-top: 30px;">
                    <button class="btn btn-secondary" onclick="showScreen('main-menu-screen')">◀ 返回</button>
                    <button class="btn btn-primary" onclick="confirmTeacherSelection()" id="confirm-teacher-btn" disabled>✅ 确认选择</button>
                </div>
            </div>
        </div>
        
        <!-- 主菜单界面 -->
        <div id="main-menu-screen" class="screen active">
            <div class="menu">
                <h2 class="menu-title">游戏副本</h2>
                <div class="menu-buttons">
                    <button class="btn btn-primary" onclick="showTeacherSelection()">开始新的游戏</button>
                    <button class="btn btn-secondary" onclick="loadGame()">读取存档</button>
                    <button class="btn btn-danger" onclick="exitGame()">退出游戏</button>
                </div>
            </div>
            
            <div class="message-box" id="message-area">
                <p>欢迎来到《期末周》网页版游戏！这是一场关于生存与学习的挑战，你需要通过7天的考验。每天都有不同的考试等着你，收集道具，管理资源，努力获得好成绩吧！</p>
            </div>
        </div>
        
            <!-- 游戏主界面 -->
            <div id="game-screen" class="screen">
                <div class="day-info" id="day-info">
                    <h2>📅 第 <span id="current-day">1</span> 天</h2>
                    <p>📘 今天的考试科目是: <span id="exam-name">通识选修课</span></p>
                    <p>📈 考试难度: <span id="exam-difficulty">1</span>/7</p>
                </div>
                
                <!-- 操作次数 -->
                <div style="text-align: right; margin-bottom: 10px;" id="actions-counter-container" class="hidden">
                    <div class="actions-counter-container">
                        <span class="actions-counter-label">今日操作次数:</span>
                        <span class="actions-counter" id="actions-counter">0</span>
                        <span style="color: white; font-weight: bold; margin-left: 5px;">/7</span>
                    </div>
                </div>
            
            <div class="event-box hidden" id="event-box">
                <h3>🔔 事件</h3>
                <p id="event-name"></p>
                <p id="event-description"></p>
            </div>
            <div class="message-box hidden" id="item-box">
                <h3>🎁 获得道具</h3>
                <p id="item-name"></p>
                <p id="item-description"></p>
            </div>
            
            <!-- 特殊事件界面 -->
            <div class="event-box hidden" id="special-event-box">
                <h3>🔔 特殊事件</h3>
                <p id="special-event-name"></p>
                <p id="special-event-description"></p>
                <div class="actions">
                    <button class="btn btn-success" onclick="acceptEvent()">接受</button>
                    <button class="btn btn-secondary" onclick="declineEvent()">拒绝</button>
                </div>
            </div>
            
            <div class="inventory hidden" id="inventory">
                <h3>🎒 背包物品</h3>
                <ul class="item-list" id="inventory-list"></ul>
            </div>
            
            <!-- 学习问题区域 -->
            <div class="study-quiz-container" id="study-quiz-container">
                <div class="study-quiz-question" id="study-quiz-question"></div>
                <div class="study-quiz-options" id="study-quiz-options"></div>
                <button class="submit-answer-btn" id="submit-answer-btn" onclick="submitStudyAnswer()" disabled>提交答案</button>
            </div>
            
            <div class="menu">
                <h2 class="menu-title">📋 日常活动</h2>
                <div class="menu-buttons">
                    <button class="btn btn-primary" onclick="study()">复习功课</button>
                    <button class="btn btn-success" onclick="rest()">休息恢复</button>
                    <button class="btn btn-warning" onclick="showUseItemMenu()">使用道具</button>
                    <button class="btn btn-info" onclick="takeExam()">参加考试</button>
                    <button class="btn btn-secondary" onclick="takeQuiz()">随堂测试</button>
                    <button class="btn btn-danger" onclick="showMainMenu()">退出游戏</button>
                </div>
            </div>
            
            <div class="message-box" id="message-area">
                <p>欢迎来到《期末周》网页版游戏！这是一场关于生存与学习的挑战，你需要通过7天的考验。每天都有不同的考试等着你，收集道具，管理资源，努力获得好成绩吧！</p>
            </div>
        </div>
        
        <!-- 使用道具界面 -->
        <div id="use-item-screen" class="screen">
            <h2 class="center">🎒 使用道具</h2>
            
            <div class="inventory">
                <h3>背包物品</h3>
                <ul class="item-list" id="use-item-list"></ul>
            </div>
            
            <div class="actions">
                <button class="btn btn-secondary" onclick="showGameScreen()">返回</button>
            </div>
        </div>
        
        <!-- 考试界面 -->
        <div id="exam-screen" class="screen">
            <div class="exam-info">
                <h2 class="center">🎓 <span id="exam-title">考试</span> 考试</h2>
                <p>📊 根据你的知识水平，基础分数为: <span id="base-score">0</span>分</p>
            </div>
            
            <div class="message-box" id="exam-item-prompt">
                <h3>💡 你想使用考试道具来提高分数吗?</h3>
            </div>
            
            <div class="inventory hidden" id="exam-items">
                <h3>📋 可用的考试道具</h3>
                <ul class="item-list" id="exam-item-list"></ul>
            </div>
            
            <div class="actions">
                <button class="btn btn-success" onclick="completeExam()">不使用道具，直接完成考试</button>
                <button class="btn btn-secondary" onclick="showGameScreen()">返回</button>
            </div>
        </div>
        
        <!-- 考试结果界面 -->
        <div id="exam-result-screen" class="screen">
            <div class="exam-info">
                <h2 class="center">🎓 考试结果</h2>
                <p>🏁 你获得了 <span id="exam-score">0</span> 分!</p>
                <p>💬 <span id="exam-comment"></span></p>
            </div>
            
            <div class="actions">
                <button class="btn btn-primary" onclick="nextDay()">继续</button>
            </div>
        </div>
        
        <!-- 游戏结束界面 -->
        <div id="game-end-screen" class="screen">
            <div class="game-over">
                <h2>🎓 期末周结束了</h2>
                <div class="final-score">🏆 最终总分: <span id="final-score">0</span></div>
                <p id="ending-text"></p>
                <img id="ending-cg" class="ending-cg" style="display:none; max-width:100%; height:auto; margin-top:20px; border-radius:10px;" />
                <div class="actions">
                    <button class="btn btn-primary" onclick="showMainMenu()">返回主菜单</button>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        let gameState = null;
        let currentExam = null;
        let examBaseScore = 0;
        let currentEvent = null;
        isProcessingAction = false; // 添加标志以防止重复操作
        let selectedTeacher = null; // 添加老师选择变量
        
        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 可以在这里添加初始化代码
        });

        // 切换BGM播放状态
        function toggleBGM() {
            const bgm = document.getElementById('bgm');
            const bgmControl = document.querySelector('.bgm-control');
            
            if (bgm.paused) {
                bgm.play();
                bgmControl.textContent = '🔇';
            } else {
                bgm.pause();
                bgmControl.textContent = '🔊';
            }
        }
        
        // 显示老师选择界面
        function showTeacherSelection() {
            // 隐藏所有屏幕
            document.querySelectorAll('.screen').forEach(screen => {
                screen.classList.remove('active');
            });
            
            // 显示老师选择界面
            document.getElementById('teacher-selection-screen').classList.add('active');
            
            selectedTeacher = null;
            document.getElementById('confirm-teacher-btn').disabled = true;
            
            // 重置老师卡片选中状态
            document.getElementById('teacher-strict').classList.remove('selected');
            document.getElementById('teacher-kind').classList.remove('selected');
        }
        
        // 选择老师
        function selectTeacher(teacherType) {
            selectedTeacher = teacherType;
            document.getElementById('confirm-teacher-btn').disabled = false;
            
            // 更新老师卡片选中状态
            if (teacherType === 'strict') {
                document.getElementById('teacher-strict').classList.add('selected');
                document.getElementById('teacher-kind').classList.remove('selected');
            } else {
                document.getElementById('teacher-kind').classList.add('selected');
                document.getElementById('teacher-strict').classList.remove('selected');
            }
        }
        
        // 确认老师选择
        async function confirmTeacherSelection() {
            if (!selectedTeacher) {
                showMessage('请先选择一位老师！', 'warning');
                return;
            }
            
            try {
                const response = await fetch('/api/start_new_game', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({teacher_type: selectedTeacher})
                });
                
                gameState = await response.json();
                updatePlayerStatus();
                showScreen('game-screen');
                document.getElementById('actions-counter-container').classList.remove('hidden'); // 显示操作次数
                await nextDay();
            } catch (error) {
                showMessage('无法开始新游戏: ' + error.message, 'danger');
            }
        }
        
        // 显示指定屏幕
        function showScreen(screenId) {
            // 隐藏所有屏幕
            document.querySelectorAll('.screen').forEach(screen => {
                screen.classList.remove('active');
            });
            
            // 显示指定屏幕
            document.getElementById(screenId).classList.add('active');
        }
        
        // 进入下一天
        async function nextDay() {
            // 防止重复点击
            if (isProcessingAction) return;
            
            isProcessingAction = true;
            
            if (!gameState) {
                isProcessingAction = false;
                return;
            }
            
            try {
                const response = await fetch('/api/next_day', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(gameState)
                });
                
                const result = await response.json();
                
                if (result.type === 'game_end') {
                    // 游戏结束
                    gameState = result.game_state;
                    showGameEnd();
                    return;
                }
                
                gameState = result.game_state;
                
                // 更新考试信息
                currentExam = result.exam;
                document.getElementById('exam-name').textContent = currentExam.name;
                document.getElementById('exam-difficulty').textContent = currentExam.difficulty;
                
                // 显示随机事件
                if (result.event) {
                    document.getElementById('event-name').textContent = result.event.name;
                    document.getElementById('event-description').textContent = result.event.description;
                    document.getElementById('event-box').classList.remove('hidden');
                    // 设置当前事件
                    currentEvent = result.event;
                } else {
                    document.getElementById('event-box').classList.add('hidden');
                    currentEvent = null;
                }
                
                // 显示随机道具
                if (result.item) {
                    document.getElementById('item-name').textContent = result.item.name;
                    document.getElementById('item-description').textContent = result.item.description;
                    document.getElementById('item-box').classList.remove('hidden');
                } else {
                    document.getElementById('item-box').classList.add('hidden');
                }
                
                updatePlayerStatus();
                
                // 每天开始时触发随机事件
                const needEventChoice = triggerDailyEvent();
                
                // 显示游戏主界面（除非需要事件选择）
                if (!needEventChoice) {
                    showScreen('game-screen');
                }
            } catch (error) {
                showMessage('无法进入下一天: ' + error.message, 'danger');
            } finally {
                // 确保在操作完成后重置标志
                isProcessingAction = false;
            }
        }
        
        // 更新天数节点UI
        function updateDaysProgress() {
            if (!gameState) return;
            
            const currentDay = gameState.day;
            
            // 重置所有节点
            for (let i = 1; i <= 7; i++) {
                const node = document.getElementById(`day-node-${i}`);
                node.classList.remove('current', 'completed');
                if (i < currentDay) {
                    node.classList.add('completed');
                } else if (i === currentDay) {
                    node.classList.add('current');
                }
            }
        }
        
        // 更新操作次数显示
        function updateActionsCounter() {
            if (!gameState) return;
            
            const actionsToday = gameState.actions_today || 0;
            document.getElementById('actions-counter').textContent = actionsToday;
        }
        
        // 更新玩家状态显示
        function updatePlayerStatus() {
            if (!gameState || !gameState.player) return;
            
            const player = gameState.player;
            
            // 更新生命值
            const healthPercent = player.health;
            document.getElementById('health-bar').style.width = healthPercent + '%';
            document.getElementById('health-text').textContent = player.health + '/100';
            
            // 更新精力值
            const energyPercent = player.energy;
            document.getElementById('energy-bar').style.width = energyPercent + '%';
            document.getElementById('energy-text').textContent = player.energy + '/100';
            
            // 更新知识值
            document.getElementById('knowledge-bar').style.width = Math.min(player.knowledge, 100) + '%';
            document.getElementById('knowledge-text').textContent = player.knowledge;
            
            // 更新分数
            document.getElementById('score-text').textContent = player.score;
            
            // 更新天数
            document.getElementById('day-text').textContent = '第' + gameState.day + '天';
            document.getElementById('current-day').textContent = gameState.day;
            
            // 更新天数节点UI
            updateDaysProgress();
            
            // 更新操作次数
            updateActionsCounter();
            
            // 更新背包显示
            updateInventory();
        }
        
        // 更新背包显示
        function updateInventory() {
            if (!gameState || !gameState.player) return;
            
            const inventory = gameState.player.inventory;
            const inventoryList = document.getElementById('inventory-list');
            const useItemList = document.getElementById('use-item-list');
            const examItemList = document.getElementById('exam-item-list');
            
            // 清空现有列表
            inventoryList.innerHTML = '';
            useItemList.innerHTML = '';
            examItemList.innerHTML = '';
            
            if (inventory.length > 0) {
                // 显示背包
                document.getElementById('inventory').classList.remove('hidden');
                
                // 填充普通背包列表
                inventory.forEach((item, index) => {
                    const li = document.createElement('li');
                    li.innerHTML = `<strong>${item.name}</strong> - ${item.description}`;
                    inventoryList.appendChild(li);
                });
                
                // 填充使用道具界面列表
                inventory.forEach((item, index) => {
                    const li = document.createElement('li');
                    li.innerHTML = `
                        <strong>${item.name}</strong> - ${item.description}
                        <button class="btn btn-success" style="float: right;" onclick="useItem(${index})">使用</button>
                    `;
                    useItemList.appendChild(li);
                });
                
                // 填充考试道具列表
                const examItems = inventory.filter(item => item.effect === 'exam');
                if (examItems.length > 0) {
                    examItems.forEach((item, index) => {
                        const li = document.createElement('li');
                        li.innerHTML = `
                            <strong>${item.name}</strong> - ${item.description}
                            <button class="btn btn-success" style="float: right;" onclick="useExamItem(${index})">使用</button>
                        `;
                        examItemList.appendChild(li);
                    });
                    document.getElementById('exam-items').classList.remove('hidden');
                } else {
                    document.getElementById('exam-items').classList.add('hidden');
                }
            } else {
                // 隐藏背包
                document.getElementById('inventory').classList.add('hidden');
                document.getElementById('exam-items').classList.add('hidden');
            }
        }
        
        // 开始新游戏 - 现在已改为 showTeacherSelection()
        // 保留原函数作为备用
        async function startNewGame() {
            try {
                const response = await fetch('/api/start_new_game', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                gameState = await response.json();
                updatePlayerStatus();
                showScreen('game-screen');
                await nextDay();
            } catch (error) {
                showMessage('无法开始新游戏: ' + error.message, 'danger');
            }
        }
        
        // 保存游戏
        async function saveGame() {
            try {
                const response = await fetch('/api/save_game', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                const result = await response.json();
                
                if (result.success) {
                    showMessage('游戏保存成功！', 'success');
                } else {
                    showMessage('保存失败: ' + result.message, 'danger');
                }
            } catch (error) {
                showMessage('保存失败: ' + error.message, 'danger');
            }
        }
        
        // 加载游戏
        async function loadGame() {
            try {
                const response = await fetch('/api/load_game', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                const result = await response.json();
                
                if (result.success) {
                    gameState = result.game_state;
                    updatePlayerStatus();
                    showScreen('game-screen');
                    showMessage('游戏加载成功！', 'success');
                } else {
                    showMessage('加载失败: ' + result.message, 'danger');
                }
            } catch (error) {
                showMessage('加载失败: ' + error.message, 'danger');
            }
        }
        
        // 触发每日事件
        function triggerDailyEvent() {
            // 检查是否有待处理的事件
            if (currentEvent) {
                // 检查是否是自动处理事件
                if (currentEvent.name === "网络崩溃") {
                    // 自动处理事件
                    processEvent();
                    return false; // 不需要用户选择
                }
                // 需要用户选择的事件
                showSpecialEvent(currentEvent);
                return true;
            }
            return false; // 没有事件需要处理
        }

        // 复习功课
        async function study() {
            // 如果正在处理操作，防止重复点击
            if (isProcessingAction) return;
            
            // 检查是否还有操作次数
            if (gameState.actions_today >= 7) {
                showMessage('每天只能进行7次操作！考试时间到了，不能进行别的操作了哦', 'danger');
                showExamAlert();
                return;
            }
            
            // 每次操作前都触发事件（仅当没有待处理事件时）
            if (currentEvent) {
                // 如果是自动处理事件，处理它
                if (currentEvent.name === "网络崩溃") {
                    await processEvent();
                } else {
                    // 如果是非自动事件，需要用户处理
                    showMessage('请先处理当前事件！', 'warning');
                    return;
                }
            }
            
            // 根据老师类型检查体力值是否足够
            const teacherType = gameState.teacher_type || 'kind';
            const energyCost = teacherType === 'strict' ? 15 : 10;
            
            if (gameState.player.energy < energyCost) {
                showMessage('你的精力不足，无法复习功课！', 'danger');
                return;
            }
            
            // 发起带问题的学习请求
            isProcessingAction = true;
            
            try {
                const response = await fetch('/api/study_with_questions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                const result = await response.json();
                checkActionLimit(result);
                
                if (result.success) {
                    if (result.actions_today !== undefined) {
                        gameState.actions_today = result.actions_today;
                        updateActionsCounter(); // 更新操作次数显示
                    }
                    // 显示学习问题
                    showStudyQuiz(result.question, result.subject);
                } else {
                    if (result.message) {
                        showMessage(result.message, 'danger');
                    }
                    isProcessingAction = false;
                }
            } catch (error) {
                showMessage('操作失败: ' + error.message, 'danger');
                isProcessingAction = false;
            }
        }
        
        // 显示学习问题
        function showStudyQuiz(question, subject) {
            const studyQuizContainer = document.getElementById('study-quiz-container');
            const studyQuestionElement = document.getElementById('study-quiz-question');
            const studyOptionsElement = document.getElementById('study-quiz-options');
            
            // 设置问题和选项
            studyQuestionElement.innerHTML = `${subject} - ${question.question}`;
            
            // 清空选项
            studyOptionsElement.innerHTML = '';
            
            // 添加选项
            question.options.forEach((option, index) => {
                const optionElement = document.createElement('div');
                optionElement.className = 'study-quiz-option';
                optionElement.textContent = option;
                optionElement.onclick = () => selectStudyOption(optionElement, index);
                studyOptionsElement.appendChild(optionElement);
            });
            
            // 保存正确答案和问题信息
            studyQuizContainer.dataset.correctAnswer = question.answer;
            studyQuizContainer.dataset.subject = subject;
            
            // 显示学习问题容器
            studyQuizContainer.style.display = 'block';
            
            // 禁用提交按钮
            document.getElementById('submit-answer-btn').disabled = true;
        }
        
        // 选择学习选项
        function selectStudyOption(element, index) {
            // 清除之前的选择
            const options = document.querySelectorAll('.study-quiz-option');
            options.forEach(option => option.classList.remove('selected'));
            
            // 标记当前选择
            element.classList.add('selected');
            
            // 保存选择的索引
            document.getElementById('study-quiz-container').dataset.selectedOption = index;
            
            // 启用提交按钮
            document.getElementById('submit-answer-btn').disabled = false;
        }
        
        // 提交学习问题答案
        async function submitStudyAnswer() {
            const studyQuizContainer = document.getElementById('study-quiz-container');
            const selectedOption = studyQuizContainer.dataset.selectedOption;
            const correctAnswer = studyQuizContainer.dataset.correctAnswer;
            
            if (selectedOption === undefined) {
                showMessage('请选择一个答案！', 'warning');
                return;
            }
            
            try {
                const response = await fetch('/api/answer_study_question', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        selected_option: parseInt(selectedOption),
                        correct_answer: parseInt(correctAnswer)
                    })
                });
                
                const result = await response.json();
                checkActionLimit(result);
                
                if (result.success) {
                    gameState.player = result.player;
                    if (result.actions_today !== undefined) {
                        gameState.actions_today = result.actions_today;
                        updateActionsCounter(); // 更新操作次数显示
                    }
                    updatePlayerStatus();
                    showMessage(result.message, 'success');
                    
                    // 每次操作后触发随机事件
                    await triggerRandomEvent();
                } else {
                    if (result.message) {
                        showMessage(result.message, 'danger');
                    }
                }
            } catch (error) {
                showMessage('操作失败: ' + error.message, 'danger');
            } finally {
                // 隐藏学习问题容器
                studyQuizContainer.style.display = 'none';
                isProcessingAction = false;
            }
        }
        
        // 复习功课
        async function study() {
            // 如果正在处理操作，防止重复点击
            if (isProcessingAction) return;
            
            // 检查是否还有操作次数
            if (gameState.actions_today >= 7) {
                showMessage('每天只能进行7次操作！考试时间到了，不能进行别的操作了哦', 'danger');
                showExamAlert();
                return;
            }
            
            // 根据老师类型检查体力值是否足够
            const teacherType = gameState.teacher_type || 'kind';
            const energyCost = teacherType === 'strict' ? 15 : 10;
            
            if (gameState.player.energy < energyCost) {
                showMessage('你的精力不足，无法复习功课！', 'danger');
                return;
            }
            
            // 每次操作前都触发事件（仅当没有待处理事件时）
            if (currentEvent) {
                // 如果是自动处理事件，处理它
                if (currentEvent.name === "网络崩溃") {
                    await processEvent();
                } else {
                    // 如果是非自动事件，需要用户处理
                    showMessage('请先处理当前事件！', 'warning');
                    return;
                }
            }
            
            // 发起带问题的学习请求
            isProcessingAction = true;
            
            try {
                const response = await fetch('/api/study_with_questions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                const result = await response.json();
                checkActionLimit(result);
                
                if (result.success) {
                    if (result.actions_today !== undefined) {
                        gameState.actions_today = result.actions_today;
                        updateActionsCounter(); // 更新操作次数显示
                    }
                    // 显示学习问题
                    showStudyQuiz(result.question, result.subject);
                } else {
                    if (result.message) {
                        showMessage(result.message, 'danger');
                    }
                    isProcessingAction = false;
                }
            } catch (error) {
                showMessage('操作失败: ' + error.message, 'danger');
                isProcessingAction = false;
            }
        }
        
        // 休息恢复
        async function rest() {
            // 如果正在处理操作，防止重复点击
            if (isProcessingAction) return;
            
            // 检查是否还有操作次数
            if (gameState.actions_today >= 7) {
                showMessage('每天只能进行7次操作！考试时间到了，不能进行别的操作了哦', 'danger');
                showExamAlert();
                return;
            }
            
            // 检查精力是否已经满
            if (gameState.player.energy >= 100) {
                showMessage('你的精力已经满了，不需要休息！', 'info');
                return;
            }
            
            // 每次操作前都触发事件（仅当没有待处理事件时）
            if (currentEvent) {
                // 如果是自动处理事件，处理它
                if (currentEvent.name === "网络崩溃") {
                    await processEvent();
                } else {
                    // 如果是非自动事件，需要用户处理
                    showMessage('请先处理当前事件！', 'warning');
                    return;
                }
            }
            
            isProcessingAction = true;
            
            try {
                const response = await fetch('/api/rest', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                const result = await response.json();
                checkActionLimit(result);
                
                if (result.success) {
                    gameState.player = result.player;
                    if (result.actions_today !== undefined) {
                        gameState.actions_today = result.actions_today;
                    }
                    updatePlayerStatus();
                    updateActionsCounter(); // 更新操作次数显示
                    showMessage(result.message, 'success');
                    
                    // 每次操作后触发随机事件
                    await triggerRandomEvent();
                } else {
                    if (result.message) {
                        showMessage(result.message, 'danger');
                    }
                }
            } catch (error) {
                showMessage('操作失败: ' + error.message, 'danger');
            } finally {
                isProcessingAction = false;
            }
        }
        
        // 显示使用道具菜单
        function showUseItemMenu() {
            // 如果正在处理操作，防止重复点击
            if (isProcessingAction) return;
            
            updateInventory();
            showScreen('use-item-screen');
        }
        
        // 返回游戏主界面
        function showGameScreen() {
            showScreen('game-screen');
        }
        
        // 使用道具
        async function useItem(index) {
            // 如果正在处理操作，防止重复点击
            if (isProcessingAction) return;
            
            isProcessingAction = true;
            
            try {
                const response = await fetch('/api/use_item', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({item_index: index})
                });
                
                const result = await response.json();
                
                if (result.success) {
                    gameState.player = result.player;
                    if (result.actions_today !== undefined) {
                        gameState.actions_today = result.actions_today;
                    }
                    updatePlayerStatus();
                    showMessage(result.message, 'success');
                    showScreen('game-screen');
                } else {
                    showMessage(result.message, 'danger');
                }
            } catch (error) {
                showMessage('操作失败: ' + error.message, 'danger');
            } finally {
                isProcessingAction = false;
            }
        }
        
        // 参加考试
        async function takeExam() {
            // 如果正在处理操作，防止重复点击
            if (isProcessingAction) return;
            
            isProcessingAction = true;
            
            try {
                const response = await fetch('/api/take_exam', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                const result = await response.json();
                checkActionLimit(result);
                
                if (result.success === false && result.message) {
                    // 操作次数限制
                    showMessage(result.message, 'danger');
                    isProcessingAction = false;
                    return;
                }
                
                currentExam = result.exam;
                examBaseScore = result.base_score;
                
                document.getElementById('exam-title').textContent = currentExam.name;
                document.getElementById('base-score').textContent = examBaseScore;
                
                gameState.player = result.player;
                if (result.actions_today !== undefined) {
                    gameState.actions_today = result.actions_today;
                }
                updatePlayerStatus();
                
                showScreen('exam-screen');
            } catch (error) {
                showMessage('操作失败: ' + error.message, 'danger');
            } finally {
                isProcessingAction = false;
            }
        }
        
        // 接受事件
        async function acceptEvent() {
            if (!currentEvent || isProcessingAction) return;
            
            // 检查是否还有操作次数
            if (gameState.actions_today >= 7) {
                showMessage('每天只能进行7次操作！考试时间到了，不能进行别的操作了哦', 'danger');
                showExamAlert();
                // 即使操作次数用完，也要重置事件状态
                currentEvent = null;
                isProcessingAction = false;
                hideSpecialEvent();
                return;
            }
            
            isProcessingAction = true;
            
            try {
                const response = await fetch('/api/process_event', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({event_name: currentEvent.name})
                });
                
                const result = await response.json();
                checkActionLimit(result);
                
                if (result.success) {
                    gameState.player = result.player;
                    if (result.actions_today !== undefined) {
                        gameState.actions_today = result.actions_today;
                    }
                    updatePlayerStatus();
                    showMessage(result.message, 'success');
                    
                    // 如果获得了道具，显示道具信息
                    if (result.item) {
                        document.getElementById('item-name').textContent = result.item.name;
                        document.getElementById('item-description').textContent = result.item.description;
                        document.getElementById('item-box').classList.remove('hidden');
                        
                        // 3秒后隐藏道具信息
                        setTimeout(() => {
                            document.getElementById('item-box').classList.add('hidden');
                        }, 3000);
                    }
                } else {
                    showMessage(result.message, 'danger');
                }
            } catch (error) {
                showMessage('操作失败: ' + error.message, 'danger');
            } finally {
                // 重置事件和处理状态
                currentEvent = null;
                isProcessingAction = false;
                hideSpecialEvent();
            }
        }
        
        // 拒绝事件
        function declineEvent() {
            if (isProcessingAction) return;
            
            isProcessingAction = true;
            
            hideSpecialEvent();
            showMessage('你拒绝了这个事件，可以继续其他操作。', 'info');
            
            // 重置事件和处理状态
            currentEvent = null;
            isProcessingAction = false;
        }
        
        // 显示考试时间提醒
        function showExamAlert() {
            const examAlert = document.getElementById('exam-alert');
            examAlert.classList.add('show');
        }
        
        // 关闭考试时间提醒
        function closeExamAlert() {
            const examAlert = document.getElementById('exam-alert');
            examAlert.classList.remove('show');
        }
        
        // 检查是否达到操作次数上限
        function checkActionLimit(result) {
            // 如果操作失败且消息包含考试时间提醒，则显示动画
            if (result.success === false && 
                result.message && 
                result.message.includes('考试时间到了')) {
                showExamAlert();
            }
        }
        
        // 触发随机事件
        async function triggerRandomEvent() {
            try {
                const response = await fetch('/api/trigger_random_event', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(gameState)
                });
                
                const result = await response.json();
                
                // 更新游戏状态
                gameState = result.game_state;
                updatePlayerStatus();
                
                // 显示随机事件
                if (result.event) {
                    document.getElementById('event-name').textContent = result.event.name;
                    document.getElementById('event-description').textContent = result.event.description;
                    document.getElementById('event-box').classList.remove('hidden');
                    // 设置当前事件
                    currentEvent = result.event;
                    
                    // 触发每日事件（显示特殊事件界面）
                    const needEventChoice = triggerDailyEvent();
                    return needEventChoice;
                } else {
                    document.getElementById('event-box').classList.add('hidden');
                    currentEvent = null;
                }
                
                // 显示随机道具
                if (result.item) {
                    document.getElementById('item-name').textContent = result.item.name;
                    document.getElementById('item-description').textContent = result.item.description;
                    document.getElementById('item-box').classList.remove('hidden');
                    
                    // 3秒后隐藏道具信息
                    setTimeout(() => {
                        document.getElementById('item-box').classList.add('hidden');
                    }, 3000);
                } else {
                    document.getElementById('item-box').classList.add('hidden');
                }
                
                return false;
            } catch (error) {
                console.error('触发随机事件失败: ' + error.message);
                return false;
            }
        }
        
        // 退出游戏
        function exitGame() {
            if (confirm('确定要退出游戏吗？')) {
                showMessage('感谢游玩！');
                // 返回主菜单而不是尝试关闭窗口
                showMainMenu();
            }
        }
        
        // 随堂测试相关函数
        function takeQuiz() {
            // 如果正在处理操作，防止重复点击
            if (isProcessingAction) return;
            
            // 检查是否还有操作次数
            if (gameState.actions_today >= 7) {
                showMessage('每天只能进行7次操作！考试时间到了，不能进行别的操作了哦', 'danger');
                showExamAlert();
                return;
            }
            
            // 每次操作前都触发事件（仅当没有待处理事件时）
            if (currentEvent) {
                // 如果是自动处理事件，处理它
                if (currentEvent.name === "网络崩溃") {
                    processEvent();
                } else {
                    // 如果是非自动事件，需要用户处理
                    showMessage('请先处理当前事件！', 'warning');
                    return;
                }
            }
            
            isProcessingAction = true;
            
            fetch('/api/take_quiz', {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    showQuizModal(data.question);
                } else {
                    showMessage(data.message, 'danger');
                }
            })
            .catch(error => {
                showMessage('发生错误: ' + error, 'danger');
            })
            .finally(() => {
                isProcessingAction = false;
            });
        }

        function showQuizModal(question) {
            // 如果已经存在模态框则先移除
            const existingModal = document.querySelector('.modal');
            if (existingModal) {
                existingModal.remove();
            }
            
            const modal = document.createElement('div');
            modal.className = 'modal';
            modal.innerHTML = `
                <div class="modal-content">
                    <h3>随堂测试</h3>
                    <p>${question.question}</p>
                    <div class="quiz-options">
                        ${question.options.map((option, index) => 
                            `<button class="quiz-option" onclick="answerQuiz(${index}, ${question.answer})">${option}</button>`
                        ).join('')}
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
        }

        function answerQuiz(selectedAnswer, correctAnswer) {
            // 关闭模态框
            const modal = document.querySelector('.modal');
            if (modal) {
                modal.remove();
            }

            // 提交答案
            fetch('/api/answer_quiz', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    answer: selectedAnswer,
                    correct_answer: correctAnswer
                })
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    gameState.player = data.player;
                    if (data.actions_today !== undefined) {
                        gameState.actions_today = data.actions_today;
                    }
                    updatePlayerStatus();
                    showMessage(data.message, 'success');
                    
                    // 如果获得了道具，显示道具信息
                    if (data.item) {
                        document.getElementById('item-name').textContent = data.item.name;
                        document.getElementById('item-description').textContent = data.item.description;
                        document.getElementById('item-box').classList.remove('hidden');
                        
                        // 3秒后隐藏道具信息
                        setTimeout(() => {
                            document.getElementById('item-box').classList.add('hidden');
                        }, 3000);
                    }
                } else {
                    showMessage(data.message, 'danger');
                }
            })
            .catch(error => {
                showMessage('发生错误: ' + error, 'danger');
            });
        }
        
        // 显示主菜单
        function showMainMenu() {
            // 重置游戏状态
            gameState = null;
            currentExam = null;
            currentEvent = null;
            isProcessingAction = false;
            examBaseScore = 0;
            
            // 清空玩家状态显示
            document.getElementById('health-bar').style.width = '100%';
            document.getElementById('health-text').textContent = '100/100';
            document.getElementById('energy-bar').style.width = '100%';
            document.getElementById('energy-text').textContent = '100/100';
            document.getElementById('knowledge-bar').style.width = '0%';
            document.getElementById('knowledge-text').textContent = '0';
            document.getElementById('score-text').textContent = '0';
            document.getElementById('day-text').textContent = '第1天';
            
            // 重置天数节点UI
            for (let i = 1; i <= 7; i++) {
                const node = document.getElementById(`day-node-${i}`);
                node.classList.remove('current', 'completed');
                if (i === 1) {
                    node.classList.add('current');
                }
            }
            
            // 隐藏可能显示的面板
            document.getElementById('event-box').classList.add('hidden');
            document.getElementById('item-box').classList.add('hidden');
            document.getElementById('special-event-box').classList.add('hidden');
            document.getElementById('inventory').classList.add('hidden');
            
            // 重置操作次数显示
            document.getElementById('actions-counter').textContent = '0';
            
            // 重置考试相关信息
            document.getElementById('exam-name').textContent = '通识选修课';
            document.getElementById('exam-difficulty').textContent = '1';
            document.getElementById('current-day').textContent = '1';
            
            // 清空消息区域
            const messageArea = document.getElementById('message-area');
            if (messageArea) {
                messageArea.innerHTML = '<p>欢迎来到《期末周》网页版游戏！这是一场关于生存与学习的挑战，你需要通过7天的考验。每天都有不同的考试等着你，收集道具，管理资源，努力获得好成绩吧！</p>';
            }
            
            // 显示主菜单界面
            showScreen('main-menu-screen');
        }
        
        // 重置游戏
        function resetGame() {
            gameState = null;
            currentEvent = null;
            isProcessingAction = false;
            
            // 重置UI
            initDaysProgress();
            updatePlayerStatus();
            
            // 重置操作次数显示
            document.getElementById('actions-counter').textContent = '0';
            document.getElementById('actions-counter-container').classList.add('hidden'); // 隐藏操作次数
            
            // 重置考试相关信息
            document.getElementById('exam-name').textContent = '通识选修课';
            document.getElementById('exam-difficulty').textContent = '1';
            document.getElementById('current-day').textContent = '1';
            
            // 清空消息区域
            const messageArea = document.getElementById('message-area');
            if (messageArea) {
                messageArea.innerHTML = '<p>欢迎来到《期末周》网页版游戏！这是一场关于生存与学习的挑战，你需要通过7天的考验。每天都有不同的考试等着你，收集道具，管理资源，努力获得好成绩吧！</p>';
            }
            
            // 显示主菜单界面
            showScreen('main-menu-screen');
        }
        
        // 显示特殊事件
        function showSpecialEvent(event) {
            document.getElementById('special-event-name').textContent = event.name;
            document.getElementById('special-event-description').textContent = event.description;
            document.getElementById('special-event-box').classList.remove('hidden');
        }
        
        // 隐藏特殊事件
        function hideSpecialEvent() {
            document.getElementById('special-event-box').classList.add('hidden');
        }
        
        // 处理事件（接受）
        async function processEvent() {
            if (isProcessingAction || !currentEvent) return;
            
            isProcessingAction = true;
            
            try {
                const response = await fetch('/api/process_event', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({event_name: currentEvent.name})
                });
                
                const result = await response.json();
                checkActionLimit(result);
                
                if (result.success) {
                    gameState.player = result.player;
                    if (result.actions_today !== undefined) {
                        gameState.actions_today = result.actions_today;
                    }
                    updatePlayerStatus();
                    showMessage(result.message, 'success');
                    
                    // 如果获得了道具，显示道具信息
                    if (result.item) {
                        document.getElementById('item-name').textContent = result.item.name;
                        document.getElementById('item-description').textContent = result.item.description;
                        document.getElementById('item-box').classList.remove('hidden');
                        
                        // 3秒后隐藏道具信息
                        setTimeout(() => {
                            document.getElementById('item-box').classList.add('hidden');
                        }, 3000);
                    }
                } else {
                    showMessage(result.message, 'danger');
                }
            } catch (error) {
                showMessage('操作失败: ' + error.message, 'danger');
            } finally {
                // 重置事件和处理状态
                currentEvent = null;
                isProcessingAction = false;
                hideSpecialEvent();
                document.getElementById('event-box').classList.add('hidden');
            }
        }
        
        // 使用考试道具
        async function useExamItem(index) {
            try {
                const response = await fetch('/api/use_exam_item', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({item_index: index})
                });
                
                const result = await response.json();
                
                if (result.success) {
                    gameState.player = result.player;
                    updatePlayerStatus();
                    showMessage(result.message, 'success');
                    completeExam(result.bonus || 0);
                } else {
                    showMessage(result.message, 'danger');
                }
            } catch (error) {
                showMessage('操作失败: ' + error.message, 'danger');
            }
        }
        
        // 完成考试
        async function completeExam(bonus = 0) {
            // 防止重复点击
            if (isProcessingAction) return;
            
            isProcessingAction = true;
            
            try {
                const response = await fetch('/api/complete_exam', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({item_bonus: bonus})
                });
                
                const result = await response.json();
                
                gameState.player = result.player;
                
                document.getElementById('exam-score').textContent = result.score;
                document.getElementById('exam-comment').textContent = result.comment;
                
                if (result.game_over) {
                    showGameEnd();
                    return;
                }
                
                gameState.day = result.next_day;
                updatePlayerStatus();
                showScreen('exam-result-screen');
            } catch (error) {
                showMessage('操作失败: ' + error.message, 'danger');
            } finally {
                // 确保在操作完成后重置标志
                isProcessingAction = false;
            }
        }
        
        // 显示游戏结束界面
        function showGameEnd() {
            if (!gameState || !gameState.player) return;
            
            const score = gameState.player.score;
            document.getElementById('final-score').textContent = score;
            
            // 计算加权平均分
            let totalWeightedScore = 0;
            let totalDifficulty = 0;
            if (gameState.player.exam_scores && gameState.player.exam_scores.length > 0) {
                gameState.player.exam_scores.forEach(exam => {
                    totalWeightedScore += exam.score * exam.difficulty;
                    totalDifficulty += exam.difficulty;
                });
            }
            
            let weightedAverage = totalDifficulty > 0 ? (totalWeightedScore / totalDifficulty).toFixed(2) : '0.00';
            
            let endingText = '';
            let endingImage = '';
            if (score >= 600) {
                endingText = '🌟 恭喜你以优异成绩完成了期末周！你是真正的学霸！';
                endingImage = 'ending_genius.png';
            } else if (score >= 450) {
                endingText = '👍 你成功度过了期末周，成绩还不错！';
                endingImage = 'ending_good.png';
            } else if (score >= 300) {
                endingText = '😐 虽然有些科目考得不好，但你还是勉强通过了。';
                endingImage = 'ending_pass.png';
            } else {
                endingText = '😞 这次期末周对你来说有些困难，下学期要更努力了。';
                endingImage = 'ending_fail.png';
            }
            
            // 添加加权平均分信息
            endingText += `<br><br>📊 七天总成绩（加权平均分）: ${weightedAverage}分（满分100分）`;
            
            document.getElementById('ending-text').innerHTML = endingText;
            
            // 显示对应的结局CG图
            const cgImageElement = document.getElementById('ending-cg');
            if (cgImageElement) {
                cgImageElement.src = `/static/cg/${endingImage}`;
                cgImageElement.alt = '结局CG图';
                cgImageElement.style.display = 'block';
            }
            
            showScreen('game-end-screen');
        }
        
        // 显示消息
        function showMessage(message, type = 'info') {
            const messageArea = document.getElementById('message-area');
            if (messageArea) {
                messageArea.innerHTML = `<p class="message-${type}">${message}</p>`;
                
                // 3秒后清除消息
                setTimeout(() => {
                    if (messageArea.innerHTML.includes(message)) {
                        messageArea.innerHTML = '';
                    }
                }, 3000);
            } else {
                alert(message);
            }
        }
        
        // 页面加载完成后初始化BGM控制
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化BGM控制
            initializeBGM();
        });
    </script>
    
    <!-- 引入BGM控制脚本 -->
    <script src="{{ url_for('static', filename='js/bgm.js') }}"></script>
</body>
</html>